package com.atguigu.create.singleton.type2;

/**
 * 单例模式-饿汉模式(静态代码块方式)
 */
public class SingletonTest2 {
    public static void main(String[] args) {
        Singleton singletonSource1 = Singleton.getSingletonSource();
        Singleton singletonSource2 = Singleton.getSingletonSource();
        System.out.println(singletonSource1==singletonSource2);
        System.out.println("single1:"+singletonSource1.hashCode());
        System.out.println("single2:"+singletonSource2.hashCode());
    }
}

class Singleton {
    // 1. 创建私有的构造器, 这样外部就无法new出来
    private Singleton() {
    }

    // 2. 类内容创建一个static实例并在static代码块中将之实例化
    private static Singleton singletonSource;
    static {
        singletonSource=new Singleton();
    }

    // 3. 创建一个public的static getInstance方法以获取上面的实例对象
    public static Singleton getSingletonSource(){
        return singletonSource;
    }
}
